/**  
 * @Title: LoginController.java
 * @Package com.xzit.tmms.controller
 * @Description: TODO
 * @author 董亮亮
 * @date 2016年7月1日 上午8:47:02
 * @version V1.0  
 */
package com.xzit.tmms.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xzit.tmms.common.base.BaseController;
import com.xzit.tmms.common.constant.WebConstant;
import com.xzit.tmms.common.exception.ServiceException;
import com.xzit.tmms.common.util.CommonUtil;
import com.xzit.tmms.service.user.UserService;

/**
 * @ClassName: LoginController
 * @Description: TODO
 * @author 董亮亮
 * @date 2016年7月1日 上午8:47:02
 */
@Controller
@RequestMapping("")
public class LoginController extends BaseController {

	@Resource
	private UserService userService;

	@RequestMapping("/login")
	public String login(Model model, String queryString) {
		model.addAttribute("queryString", queryString);
		return "login";
	}

	@RequestMapping("/loginValid")
	public String loginValid(RedirectAttributes attr, Model model, HttpSession session, String tmms_account,
			String password, String queryString) throws ServiceException {
		// 清空session
		session.setAttribute(WebConstant.SESSION_USER, null);
		// 查询用户
		Map<String, Object> user = null;
		user = userService.getUserByAccount(tmms_account);
		if (CommonUtil.isNotEmpty(user)) {
			// 校验密码
			if (user.get("password").toString().equals(password)) {
				// 填充登录信息
				session.setAttribute(WebConstant.SESSION_LOGIN_FLAG, WebConstant.SESSION_LOGIN_FLAG);
				session.setAttribute(WebConstant.SESSION_USER, user);
				// 跳转
				if (CommonUtil.isNotEmpty(queryString)) {
					return "redirect:" + queryString;
				}
			} else {
				model.addAttribute("tmms_account", tmms_account);
				model.addAttribute("pMsg", "密码错误");
			}
		} else {
			model.addAttribute("tmms_account", tmms_account);
			model.addAttribute("aMsg", "用户名不存在");
		}

		return "redirect:/index.action";
	}

	/**
	 * @Title: logout
	 * @Description: TODO 登出操作
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.setAttribute(WebConstant.SESSION_USER, null);
		session.invalidate();
		return "redirect:/login.action";
	}
}
